package julienD.android;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.location.Location;
import android.location.LocationManager;

/**
 * Permet de lister les stations à proximité.
 * @author Julien
 *
 */
public class StationsProches {
	

	private Context context;

	public StationsProches(Context _context) {
		context = _context;
	}
	
	public List<Station> getListe() {
		Location loc = recupererLocation();
		
		ArrayList<Station> listeNonTriee = (new BaseStations(context)).recupererListe();
		ArrayList<Station> listeTriee = new ArrayList<Station>();
		//traduction de la location
		double slat=43,slong=1;
		if (loc != null) {
			slat = loc.getLatitude();
			slong = loc.getLongitude();
		}
		
		//passage par un tableau pour le tri
		int taille = listeNonTriee.size();
		int[] tdistance = new int[taille];
		String[] tnom = new String[taille];
		
		float distance[] = new float[1];
		distance[0]=(float)0;
			
		for (int i=0;i<taille;i++){
			double dlat = (Double) listeNonTriee.get(i).getLattitude();
			double dlong = (Double) listeNonTriee.get(i).getLongitude();
			
			Location.distanceBetween(slat,slong,dlat,dlong,distance);
			tdistance[i]=(int)distance[0];
			tnom[i]=listeNonTriee.get(i).getNom();
		}
		
		int	n = taille;
		int min = 1;
		for (int i=1;i<n;i++) {
			for (int j=1;j<n;j++) {
				if (tdistance[j] < tdistance[min]){
					min = j;
				}
			}
			tdistance[min]=999999;
			
			//reconstruction liste stations:
			listeTriee.add(listeNonTriee.get(min));
		}
		
		return listeTriee;
	}

	private Location recupererLocation() {
		
		LocationManager lm =(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
		Location loc = lm .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (loc==null){
        	loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        }
        return loc;
	}
}
